# -*- coding:utf-8 -*-
from django.shortcuts import render,render_to_response,HttpResponse,HttpResponsePermanentRedirect

# Create your views here.
from .models import User

def index(request):
    username = request.COOKIES.get('username','')
    if not username:
        username = "同学"
    return render_to_response('index.html',{'username': username})

def regist(request):
    if request.method == 'POST':
        username = request.POST.get('username','')
        password = request.POST.get('password','')
        phone = request.POST.get('phone','')
        email = request.POST.get('email','')

        user_info = User()
        user_info.username = username
        user_info.password = password
        user_info.phone = phone
        user_info.email = email
        user_info.save()

        return render_to_response('reg_result.html',{'username':username})
    else:
        return render_to_response('regist.html')


def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        is_true = User.objects.filter(username=username, password=password)
        if is_true:
            response = HttpResponsePermanentRedirect('/')
            response.set_cookie('username',username,76800)
            return response
        else:
            return HttpResponse('<p>登陆失败</p><a href=/>返回主页</a>')
    return render(request,'login.html')

def logout(request):
    username = request.COOKIES.get('username','')
    repo = render(request, 'logout.html', {'username': username})
    repo.set_cookie('username','')
    return repo

def findpwd(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')

        is_true=User.objects.filter(username=username, password=old_password)
        if is_true:
            is_true.update(password=new_password)
            return HttpResponse('<p>密码修改成功</p><a href=/>返回主页</a>')
        else:
            return HttpResponse('<p>密码修改失败</p><a href=/>返回主页</a>')
    return render(request,'findpwd.html')


def reg_result(request):
    return render(request, 'reg_result.html', {'username':username})